
import axios from 'axios'
import message from '../components/message'
import {ksort} from './utils'
import md5 from 'js-md5';
const qs = require('qs')
/**
 * ======================================================================
 * 【基本说明】：
 * 网络请求模块,基于axios封装
 *
 * Created by Major_ on 18-9-12.
 * ======================================================================
 */

axios.defaults.timeout = 30000;
axios.defaults.baseURL = "http://39.108.180.1:10094/index.php/";
// axios.defaults.baseURL = "http://yun1.net/index.php/";
const headers = {
    'Content-Type': 'application/x-www-form-urlencoded'
}

  /** 
   * 计算签名
   *1、当本地无token，计算签名方式为所有参数ksort -> http_build_query -> MD5;
   *2、当本地有token，计算签名方式为token+所有参数ksort -> http_build_query -> MD5;
   */
const https = {
    /** get 请求
   * @param  {接口地址} url
   * @param  {请求参数} params
   */
  async get (url, data) {
    data.appid = 1;
    if(!sessionStorage.token){
        data.uid = sessionStorage.uid;
        data.token = '';
    }else{
        data.uid = sessionStorage.uid;
        data.token = '';
    }
    try {
      let res = await axios.get(url,{headers:headers,params: data})
      res = res.data.result;
      return new Promise((resolve) => {
        if (res.success) {
          resolve(res)
        } else {
            message.toast({
                message:`${res.error}`
            })
            return
        }
      })
    } catch (err) {
        message.toast({
            message:`服务器出错!`
        })
    }
  },
  /** post 请求
   * @param  {接口地址} url
   * @param  {请求参数} params
   */
  async post (url, data) {
    data.appid = 1;
    if(!sessionStorage.token){
        data.uid = sessionStorage.uid;
        data.token = ''; // todo 参考首次登录token计算方式
    }else{
        data.uid = sessionStorage.uid;
        data.token = ''; // todo 参考完整token计算方式
    }
    try {
      let res = await axios.post(url, qs.stringify(data),{headers:headers})
      res = res.data.result;
      return new Promise((resolve, reject) => {
          
        if (res.success) {
            resolve(res)
        } else {
            // console.log(res)
            resolve(res)
            message.toast({
                message:`${res.error}`
            })
            return 
        }
      })
    } catch (err) {
        message.toast({
            message:`服务器出错!`
        })
    }
  },
}

export default https